<template>
  <div>
    <el-card style="width: 50%; margin: 0 auto;">
      <el-form
          ref="formRef"
          :model="data.form"
          label-width="80px"
          style="padding-right: 20px"
      >
        <div style="display: flex; flex-direction: column; align-items: center; margin-bottom: 20px">
          <div class="avatar-tip">支持 jpg、png 格式，大小不超过 5MB</div>
        </div>
        <el-form-item label="Id：">
          <el-input v-model="data.form.id" autocomplete="off" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="账号：">
          <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入账号" disabled/>
        </el-form-item>
        <el-form-item label="密码：">
          <el-input v-model="data.form.password" autocomplete="off" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="角色：">
          <el-input v-model="data.form.role" autocomplete="off" placeholder="请输入角色" disabled/>
        </el-form-item>
        <el-form-item label="手机号：" style="margin-right: 11px">
          <el-input v-model="data.form.phone" autocomplete="off" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="data.form.email" autocomplete="off" placeholder="请输入邮箱"/>
        </el-form-item>

        <div style="text-align: center">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {reactive, onMounted} from "vue";
import request from '@/utils/request.js';
import {ElMessage} from "element-plus";

const data = reactive({
  form: {
    name: '',
    username: '',
    password: '',
    role: '',
    phone: '',
    email: '',
    id: null
  }
});

// 从 localStorage 获取用户名
const loadUsername = () => {
  const userInfo = localStorage.getItem('user-Info');
  if (userInfo) {
    try {
      const parsedUserInfo = JSON.parse(userInfo);
      return parsedUserInfo.username;
    } catch (error) {
      ElMessage.error("用户信息解析失败");
      console.error(error);
      return null;
    }
  } else {
    ElMessage.error("未找到用户信息");
    return null;
  }
};

// 根据用户名从后端查询用户信息
const loadUserInfoFromBackend = async (username) => {
  if (!username) {
    ElMessage.error("未找到用户名");
    return;
  }

  try {
    const res = await request.get(`/user/finduser/${username}`);
    console.log("后端返回的数据:", res); // 打印后端返回的数据，方便调试

    if (res && res.code === 200 && res.data) {
      // 确保 res.data 包含所有需要的字段
      data.form = {
        id: res.data.id,
        name: res.data.name,
        username: res.data.username,
        password: res.data.password,
        role: res.data.role,
        phone: res.data.phone,
        email: res.data.email
      };
    } else if (res && res.code === 404) {
      ElMessage.error(res.message || "用户不存在");
    } else {
      ElMessage.error(res.message || "查询用户信息失败");
      console.error("后端返回的数据不符合预期:", res);
    }
  } catch (error) {
    ElMessage.error("查询用户信息失败，请检查网络或接口");
    console.error("接口调用失败:", error);
  }
};

// 保存修改
const save = () => {
  if (!data.form.id) {
    ElMessage.error("用户ID不存在，无法更新");
    return;
  }

  request.put('/user/update', data.form).then(res => {
    if (res.code === 200) {
      ElMessage.success("修改成功");
      // 更新 localStorage 中的用户信息
      localStorage.setItem('userInfo', JSON.stringify(data.form));
      // 刷新页面
      window.location.reload();
    } else {
      ElMessage.error(res.message);
    }
  }).catch(err => {
    ElMessage.error("修改失败");
    console.error(err);
  });
};

// 重置表单
const resetForm = () => {
  const username = loadUsername();
  if (username) {
    loadUserInfoFromBackend(username);
  }
};

// 页面加载时初始化用户信息
onMounted(() => {
  const username = loadUsername();
  if (username) {
    loadUserInfoFromBackend(username);
  }
});
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
  margin-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.avatar-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
